import re

from flask import g, render_template, redirect, request, current_app, jsonify
from flask import session

from info import db, constants
from info.libs.image_storage import storage
from info.models import House, Facility, HouseImage
from info.utils.common import user_login
from info.modules.profile import profile_blu
from info.utils.response_code import RET


@profile_blu.route("/center")
@user_login
def center():
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    data = {
        "user": user.to_dict()
    }

    return jsonify(errno=RET.OK,errmsg="ok",data=data)


@profile_blu.route("/session" , methods=["DELETE"])
def logout():

    session.pop("user_id", None)

    return jsonify(errno=RET.OK, errmsg="退出成功")


@profile_blu.route("/user_info", methods=["GET","POST"])
@user_login
def user_pic():

    user = g.user

    if request.method == "GET":
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

        data={
            "user":user.to_dict()
        }

        return jsonify(errno=RET.OK, errmsg="OK",data=data)

    try:
        image_data = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 将用户上传的图像 保存在七牛云上
    try:
        key = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    user.avatar_url = key

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    data={
        "avatar_url":constants.QINIU_DOMIN_PREFIX + key
    }

    return jsonify(errno=RET.OK, errmsg="上传头像成功", data=data)


@profile_blu.route('/base_info', methods=["POST"])
@user_login
def base_info():
    user = g.user

    name = request.json.get("name")

    user.name = name

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route("/auth", methods=["GET","POST"])
@user_login
def user_auth():
    user = g.user
    if request.method == "GET":
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

        real_name = user.real_name
        id_card = user.id_card
        data = {
            "real_name": real_name,
            "id_card": id_card
        }
        return jsonify(errno=RET.OK, errmsg="OK", data=data)

    real_name = request.json.get("real_name")
    id_card = request.json.get("id_card")

    if not all([real_name,id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")

    pattern = r"^[1-6]\d{5}[12]\d{3}(0[1-9]|1[12])(0[1-9]|1[0-9]|2[0-9]|3[01])\d{3}(\d|X|x)$"
    if not re.match(pattern, id_card):
        return jsonify(errno=RET.PARAMERR, errmsg="身份证格式错误")

    user.real_name = real_name
    user.id_card = id_card

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据库错误")

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route("/houses")
@user_login
def user_houses():
    """我的房源"""
    user = g.user
    try:
        houses_list = House.query.filter(House.user_id == user.id).order_by(House.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    house_dict = []
    for house in houses_list:
        house_dict.append(house.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg="OK", data=house_dict)


@profile_blu.route("/houses", methods=['POST'])
@user_login
def save_new_house():
    """
    发布房源
    :return:
    """
    #获取用户ID
    user_id = g.user.id

    #获取前端发过来的json数据
    # json_dict = request.get_json()
    # if not json_dict:
    #     return jsonify(errno=RET.PARAMERR, errmsg="请输入参数")

    title = request.json.get("title")
    price = request.json.get("price")
    address = request.json.get("address")
    area_id = request.json.get("area_id")
    room_count = request.json.get("room_count")
    acreage = request.json.get("acreage")
    unit = request.json.get("unit")
    capacity = request.json.get("capacity")
    beds = request.json.get("beds")
    deposit = request.json.get("deposit")
    min_days = request.json.get("min_days")
    max_days = request.json.get("max_days")

    if not all([title,price,address,area_id,room_count,acreage,unit,capacity,beds,deposit,min_days,max_days]):
        return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
    try:
        price = int(float(price) * 100)
        deposit = int(float(deposit) * 100)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    #设置数据到模型
    house = House()
    house.user_id = user_id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days

    facility = request.json.get("facility")
    if facility:
        facilities = Facility.query.filter(Facility.id.in_(facility)).all()
        house.facilities = facilities

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg="OK",data={'house_id':house.id})


@profile_blu.route('/houses/<int:house_id>/images', methods=['POST'])
@user_login
def upload_house_pic(house_id):
    """
    上传房源图片
    :param house_id:房源id
    :return:
    """

    # 取到图片文件
    image_file = request.files.get('house_image')
    if not image_file:
        return jsonify(errno=RET.PARAMERR, errmsg="未选择图片")

    # 查询房屋数据
    try:
        house = House.query.filter_by(id=house_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询房屋数据失败")

    if not house:
        return jsonify(errno=RET.NODATA, errmsg="未查询到对应房屋")

    # 使用七牛云上传图片
    image_data = image_file.read()
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 判断房屋是否有主图片，如果没有，则设置
    if not house.index_image_url:
        house.index_image_url = image_name

    # 生成房屋图片模型并保存至数据库
    house_image = HouseImage()
    house_image.house_id = house_id
    house_image.url = image_name

    try:
        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存房屋图片失败")

    # 返回数据
    image_url = constants.QINIU_DOMIN_PREFIX + image_name
    print(image_url)
    return jsonify(errno=RET.OK, errmsg="OK", data={'url': image_url})




